package service

import (
	"PDF/modules"
	"fmt"
	"io"
	"math/rand"
	"os"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func Upload(c *gin.Context) {
	// writer := c.Writer
	req := c.Request
	srcFile, head, err := req.FormFile("file")
	if err != nil {
		fmt.Println("文件获取失败", err)
	}
	suffix := ".pdf"
	ofileName := head.Filename
	tem := strings.Split(ofileName, ".")
	if len(tem) > 1 {
		suffix = "." + tem[len(tem)-1]
	}

	fileName := fmt.Sprintf("%d%04d%s", time.Now().Unix(), rand.Int31(), suffix)
	dstFile, err := os.Create("./pdf/upload/" + fileName)
	if err != nil {
		fmt.Println("文件创建失败", err)
	}
	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		fmt.Println("文件信息拷贝失败", err)
	}
	url := "http://localhost:8080/pdf/upload/" + fileName
	c.JSON(200, gin.H{
		"Code": 0,
		"Data": url,
		"msg":  "文件上传成功",
	})
}

func FileHandle(c *gin.Context) {
	modules.SplitandAddWaterMark()
}
